#!/usr/bin/python
import xmpp
import sys
from datetime import datetime
from random import choice
from jablit.utils import load_or_create_conf
conf = load_or_create_conf()

class Client:
    def __init__(self, client, jid, password, server):
        self.client = client
        self.password = password
        self.jid = jid
        self.server = server
        self.buffered_messages = []
        self.show = 1
        try:
            self.writers = getattr(conf[0], "writers")
        except AttributeError:
            self.writers = []

    def write_message(self, message):
        for writer in self.writers:
            writer.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S - ") \
                + message + "\n")

    def register_handlers(self):
        self.client.RegisterHandler('message', self.xmpp_message)

    def get_printname_fromjid(self, fromjid):
        printname = fromjid.split('@')[0].encode('utf-8')
        if fromjid in conf[0].aliases:
            printname = conf[0].aliases[fromjid].encode('utf-8')
        return printname

    def print_message(self, message):
        if not self.show:
            self.buffered_messages.append(message)
        else:
            print message.encode('utf-8')

    def xmpp_message(self, con, event):
        etype = event.getType()
        fromjid = event.getFrom().getStripped().split('/')[0]
        printname = self.get_printname_fromjid(fromjid)
        if self.show:
            if event.getTags('composing'):
                print "%s is typing" % printname
            if event.getTags('paused'):
                print "%s stopped typing" % printname
        if etype in ['message', 'chat', None]:
            if event.getBody():
                message = u"%s" % printname + u" => " + event.getBody()
                self.print_message(message)
                self.write_message(message)
                self.auto_respond(fromjid, event.getBody())

    def show_buffered_messages(self):
        for message in self.buffered_messages:
            print message.encode('utf-8')
        self.buffered_messages = []

    def stdio_message(self, message, jid):
        alias = self.get_printname_fromjid(jid)
        self.write_message(u"me => %s" % alias + u": " + message)
        m = xmpp.protocol.Message(to=jid, body=message, typ='chat')
        self.client.send(m)

    def auto_respond(self, fromjid, message):
        if not conf[0].auto_messages:
            return
        for jid_re in conf[0].auto_messages:
            match_jid = jid_re[0].match(fromjid)
            if match_jid:
                for incoming_msg_re in jid_re[1].keys():
                    match_msg = incoming_msg_re.match(message)
                    tosend = choice(jid_re[1][incoming_msg_re])
                    if match_msg:
                        self.stdio_message(tosend, fromjid)
                        self.print_message(u"%s <= %s (auto)" % \
                                       (self.get_printname_fromjid(fromjid),
                                        tosend))

    def set_status(self, status="online", text=""):
        presence = xmpp.Presence()
        presence.setStatus(text)
        if status == "online":
            presence.setShow("")
        else:
            presence.setShow(status)
        self.client.send(presence)

    def xmpp_connect(self):
        con = self.client.connect(self.server)
        if not con:
            sys.stderr.write('could not connect!\n')
            return False
        auth = self.client.auth(self.jid.getNode(), self.password,
                                resource=self.jid.getResource())
        if not auth:
            sys.stderr.write('could not authenticate!\n')
            return False
        self.register_handlers()
        return con
